package com.springspirit.monitor;

import java.util.Calendar;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.stereotype.Service;

import com.espertech.esper.client.EPRuntime;
import com.springspirit.framework.message.LogMessage;
import com.springspirit.monitor.cep.EventManager;

@Service("eventAggregator")
public class EventAggregatorImpl implements EventAggregator{
	
	private final Log logger = LogFactory.getLog(EventAggregatorImpl.class);
	
	@Autowired
	private EventManager eventManager;
	
//	public void setEventManager(EventManager eventManager){
//		this.eventManager = eventManager;
//	}
	
	@Autowired
	private JmsTemplate jmsTemplate;
	
//	public void setJmsTemplate(JmsTemplate jmsTemplate){
//		this.jmsTemplate = jmsTemplate;
//	}
	
	/*
	 * jmsTemplate을 이용하여 서버 로그 메시지를 수신 및 리턴하고 CEP Engine으로 메시지를 전송한다.
	 * @see com.springspirit.monitor.EventAggregator#receiveJmsMessage()
	 */
	@Override
	public LogMessage receiveJmsMessage() {
		
		if(logger.isDebugEnabled()){
	    	logger.debug("EventAggregatorImpl receiveJmsMessage: start time: " + Calendar.getInstance().getTimeInMillis());
	    }
	    
		LogMessage logMessage = (LogMessage)jmsTemplate.receiveAndConvert();
	 
		if(logger.isDebugEnabled()){
	    	logger.debug("EventAggregatorImpl receiveJmsMessage: end time: " + Calendar.getInstance().getTimeInMillis());
	    }
//	    
//	    if(logger.isDebugEnabled()){
//	    	if(logMessage == null){
//	    		logger.debug("EventAggregatorImpl receiveJmsMessage: logMessage is null ");
//	    	} else {
//	    		logger.debug("EventAggregatorImpl receiveJmsMessage: logMessage is not null ");
//	    	}
//	    }
//	    
//	    if(logMessage ==  null) return null;
	    
	    
		this.sendEventToCEPEngine(logMessage);
		
		return logMessage;
	}
	
	/*
	 * 서버 로그 메시지를 CEP Engine으로 전송한다.
	 * @see com.springspirit.monitor.EventAggregator#sendEventToCEPEngine(com.springspirit.framework.message.LogMessage)
	 */
	public void sendEventToCEPEngine(LogMessage logMessage){		
		
//		if(logger.isDebugEnabled()){
//			logger.debug("[JMS] EventAggregator called!: " + logMessage.toString());
//		}
				
		// Event 생성
		
		EPRuntime epRuntime = eventManager.getCepEngineRuntime();
		
		epRuntime.sendEvent(logMessage);
	}
}
